package com.java.jvm;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

class BreakParentClassLoader extends ClassLoader{
    private String baseDir;
    public BreakParentClassLoader(String baseDir){
        this.baseDir=baseDir;
    }
    @Override
    protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
        //1.先自己加载
        try {
            return findClass(name);
        }catch (Exception e) {
        //2.自己不能加载的再用双亲委派去加载
            e.printStackTrace();
            return super.loadClass(name, resolve);

        }
    }


    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        //1.构建类的真实路径
        String classPath=baseDir+name.replace(".", File.separator)+".class";
        //2.构建IO对象读取类文件
        InputStream in=null;
        try {
            in=new FileInputStream(classPath);
            byte[] data=new byte[in.available()];
            int  len= in.read(data);
            return defineClass(name,data,0,len);
        } catch (Exception e) {
            //e.printStackTrace();
            throw new RuntimeException(e);
        }finally {
            if(in!=null)try{in.close();}catch (Exception e){}
        }
    }
}
public class BreakParentClassLoaderTests {
    public static void main(String[] args) throws ClassNotFoundException {
        BreakParentClassLoader breakParentClassLoader=
                new BreakParentClassLoader("F:\\JSDWORK\\");
        breakParentClassLoader.loadClass("pkg.Hello");
    }
}
